package service

import (
	"api-wareway/basic/config"
	__ "api-wareway/basic/proto"
	"api-wareway/handler/model"
	"api-wareway/pkg"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"log"
	"net/http"
	"path/filepath"
	"strings"
)

func AddVideo(c *gin.Context) {
	var form model.AddVideoForm

	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "校验失败",
		})
		return
	}

	video, err := config.MemberClient.AddVideo(c, &__.AddVideoReq{
		Title:    form.Title,
		Tag:      form.Tag,
		ImageUrl: form.ImageUrl,
		Info:     form.Info,
		Status:   int64(form.Status),
		VideoUrl: form.VideoUrl,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发布成功",
		"data": video,
	})

}

func UploadFile(c *gin.Context) {
	// 文件
	file, _ := c.FormFile("file")
	etc := strings.ToLower(filepath.Ext(file.Filename))

	if !strings.Contains(".mp4.flv", etc) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "格式错误,仅支持mp4/flv",
		})
		return
	}

	file.Filename = uuid.NewString() + etc

	log.Println(file.Filename)

	url := "./file" + file.Filename
	uploadFile := pkg.UploadFile(url)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": uploadFile,
	})

}

func GetPageFile(c *gin.Context) {
	var form model.GetPageVideoForm

	err := c.ShouldBind(&form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "校验失败",
		})
		return
	}

	video, err := config.MemberClient.GetPageVideo(c, &__.GetPageVideoReq{
		Page:     int64(form.Page),
		PageSize: int64(form.PageSize),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})

}
